//
//  RTFTests.swift
//  XliffTranslatorTests
//
//  Created by 杨岑 on 2018/9/30.
//  Copyright © 2018年 杨岑. All rights reserved.
//

import XCTest

class RTFTests: XCTestCase {

    func testEncodeDecode() {
        func encodeDecodeVerify(_ text: String) {
            let encoded = RTFParser.encode(plain: text)
            let decoded = RTFParser.decode(source: encoded)
            print("original: \(text)")
            print("encoded: \(encoded)")
            print("decoded : \(decoded ?? "<none>")")
            assert(text == decoded, "Decoded text should be same with the original text")
        }
        
        encodeDecodeVerify("abc\ndef\n")
        encodeDecodeVerify("\"{\\xyz;}")
        encodeDecodeVerify("中文すべて選択")
    }
    
    func testRTFBig() {
        let file = "/Data/Documents/Word2007RTFSpec9.rtf"
        readRTFFile(file)
    }
    
    func testRTF() {
        let file = "/Data/Documents/test.rtf"
        readRTFFile(file)
    }
    
    func testRTF2() {
        let file = "/Data/Documents/Bing Daily Wallpaper/ja.xcloc/Localized Contents/BingDailyWallpaper/ja.lproj/Help.rtf"
        readRTFFile(file)
    }

    func testRTF3() {
        let file = "/Data/Documents/Bing Daily Wallpaper/ja.xcloc/Localized Contents/BingDailyWallpaper/ja.lproj/Credits.rtf"
        readRTFFile(file)
    }
    
    func readRTFFile(_ filename: String) {
        let parser = RTFParser()
        if var sourceText = try? String(contentsOfFile: filename) {
            sourceText = sourceText.trimmingCharacters(in: CharacterSet(charactersIn: " \r\n\t"))
            if let result = parser.parse(rtfSource: sourceText) {
                //print("Got \(result.sections!.count) sections")
                //visualizeRTFGroup(result, indentation: 0)
                if let composedText = RTFParser.compose(result) {
                    try? composedText.write(toFile: "/tmp/output.rtf", atomically: false, encoding: .ascii)
                    print("Composed == file RTF: \(composedText == sourceText)")
                }
            } else {
                print("Error position: \(parser.errorPosition!)")
            }
        }
    }
    
    func visualizeRTFGroup(_ group: RTFGroup, indentation: Int) {
        if let sections = group.sections {
            for section in sections {
                if let g = section as? RTFGroup {
                    visualizeRTFGroup(g, indentation: indentation + 1)
                } else if let src = section as? RTFSourceText {
                    print(String(repeating: " ", count: indentation * 2), separator: " ", terminator: "")
                    print(src)
                } else if let cmd = section as? RTFCommand {
                    print(String(repeating: " ", count: indentation * 2), separator: " ", terminator: "")
                    print(cmd)
                }
            }
        }
    }

}
